//
//  DHCommunityPublishController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/5/31.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHCommunityPublishController.h"
#import "PlaceholderTextView.h"
#import "DHPublicImage_NoCollectionCell.h"
#import "QBImagePickerController.h"
#import "UploadImageModel.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

@interface DHCommunityPublishController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, UITextViewDelegate, QBImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet PlaceholderTextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *numberLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (strong, nonatomic) NSMutableArray *imagesArr; //图片
@property (strong, nonatomic) NSMutableArray *imagesURLArr; //图片地址

@end

@implementation DHCommunityPublishController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"分享时尚片段"];
    self.navView.hidden = YES;
    
    self.textView.placeholder = @"在这里写下您的时尚片段";
    self.textView.delegate = self;
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"DHPublicImage_NoCollectionCell" bundle:nil] forCellWithReuseIdentifier:kDHPublicImage_NoCollectionCell];
}

- (NSMutableArray *)imagesArr{
    if (!_imagesArr) {
        _imagesArr = [NSMutableArray array];
    }
    return _imagesArr;
}

- (NSMutableArray *)imagesURLArr{
    if (!_imagesURLArr) {
        _imagesURLArr = [NSMutableArray array];
    }
    return _imagesURLArr;
}

- (IBAction)dismissAction:(id)sender {
    if (self.textView.text.length > 0 || self.imagesArr.count > 0) {
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"是否退出编辑?" cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (IBAction)publishAction:(id)sender {
    if (self.textView.text.length == 0) {
        [NSObject showHudTipStr:@"请输入时尚片段文字"];
    }else{
        NSMutableArray *images = [NSMutableArray array];
        [self.imagesArr enumerateObjectsUsingBlock:^(UploadImageModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.aliyunImageURL.length > 0) {
                [images addObject:obj.aliyunImageURL];
            }
        }];
        [[DHNetAPIClient shareDHNetAPIClient] request_social_publishWithParams:@{@"content":self.textView.text,@"images":images} andBlock:^(id data, NSError *error) {
            if (data) {
                [NSObject showHudTipStr:@"发布成功"];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }];
    }
}

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    if ([eventName isEqualToString:@"delete_image"]) {
        [self.imagesArr removeObject:[userInfo objectForKey:@"model"]];
        [self.collectionView reloadData];
    }
}

#pragma mark - UICollectionViewDataSource and UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.imagesArr.count >= 9) {
        return self.imagesArr.count;
    }else{
        return self.imagesArr.count + 1;
    }
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.imagesArr.count >= 9) {
        DHPublicImage_NoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDHPublicImage_NoCollectionCell forIndexPath:indexPath];
        UploadImageModel *item = [self.imagesArr objectAtIndex:indexPath.row];
        [cell.imgView setImage:item.originalImage];
        cell.imgView.contentMode = UIViewContentModeScaleAspectFill;
        if (item.aliyunImageURL.length == 0) {
            cell.aiView.hidden = NO;
            [cell.ai startAnimating];
            cell.xButton.hidden = YES;
        }else{
            cell.aiView.hidden = YES;
            [cell.ai stopAnimating];
            cell.xButton.hidden = NO;
        }
        cell.model = item;
        return cell;
    }else{
        if (indexPath.row == self.imagesArr.count) {
            DHPublicImage_NoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDHPublicImage_NoCollectionCell forIndexPath:indexPath];
            cell.imgView.contentMode = UIViewContentModeCenter;
            cell.imgView.image = [UIImage imageNamed:@"public_image_add.png"];
            cell.xButton.hidden = YES;
            return cell;
        }else{
            DHPublicImage_NoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDHPublicImage_NoCollectionCell forIndexPath:indexPath];
            UploadImageModel *item = [self.imagesArr objectAtIndex:indexPath.row];
            [cell.imgView setImage:item.originalImage];
            cell.imgView.contentMode = UIViewContentModeScaleAspectFill;
            if (item.aliyunImageURL.length == 0) {
                cell.aiView.hidden = NO;
                [cell.ai startAnimating];
                cell.xButton.hidden = YES;
            }else{
                cell.aiView.hidden = YES;
                [cell.ai stopAnimating];
                cell.xButton.hidden = NO;
            }
            cell.model = item;
            return cell;
        }
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == self.imagesArr.count) {
        UIActionSheet *actionsheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册中选择", nil];
        // 显示
        [actionsheet showInView:self.view];
    }
}

#pragma mark ---- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return (CGSize){68,86};
}

// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 4;
}

// 两个cell之间的最小间距，是由API自动计算的，只有当间距小于该值时，cell会进行换行
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 4;
}

#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {//如果是拍照
        UIImage *image;
        //如果允许编辑则获得编辑后的照片，否则获取原始照片
        if (picker.allowsEditing) {
            image=[info objectForKey:UIImagePickerControllerEditedImage];//获取编辑后的照片
        }else{
            image=[info objectForKey:UIImagePickerControllerOriginalImage];//获取原始照片
        }
        UploadImageModel *item = [[UploadImageModel alloc] init];
        item.originalImage = image;
        [self.imagesArr addObject:item];
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//保存到相簿
        [self uploadImages];
        [self.collectionView reloadData];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus ==AVAuthorizationStatusRestricted ||authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
        {
            // 无权限 引导去开启
//            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
//            if ([[UIApplication sharedApplication]canOpenURL:url]) {
//                [[UIApplication sharedApplication]openURL:url];
//            }
            [NSObject showHudTipStr:@"请打开装衣汇的摄像头权限，打开后才能使用拍照功能"];
        }else{
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController *pickerCon = [[UIImagePickerController alloc]init];
                pickerCon.sourceType = UIImagePickerControllerSourceTypeCamera;
                pickerCon.allowsEditing = NO;//是否可编辑
                pickerCon.delegate = self;
                [self presentViewController:pickerCon animated:YES completion:nil];
            }else{
                NSLog(@"手机不支持相机");
            }
        }
        
    }else if (buttonIndex == 1){
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.maximumNumberOfSelection = 9 - self.imagesArr.count;
        imagePickerController.filterType = QBImagePickerControllerFilterTypePhotos;
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
        [self presentViewController:navigationController animated:YES completion:NULL];
    }
}

#pragma mark - QBImagePickerControllerDelegate
- (void)imagePickerController:(QBImagePickerController *)imagePickerController didSelectAsset:(ALAsset *)asset{
    [self dismissImagePickerController];
}

- (void)imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissImagePickerController];
}

- (void)imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets{
    [assets enumerateObjectsUsingBlock:^(ALAsset *asset, NSUInteger idx, BOOL * _Nonnull stop) {
        ALAssetRepresentation *rep = [asset defaultRepresentation];
        CGImageRef iref = [rep fullScreenImage];
        if (iref) {
            UIImage *img = [UIImage imageWithCGImage:iref];
//            img = [NSObject imageCompressForWidth:img targetWidth:640];
            UploadImageModel *item = [[UploadImageModel alloc] init];
            item.originalImage = img;
            [self.imagesArr addObject:item];
        }
    }];
    [self uploadImages];
    [self.collectionView reloadData];
    [self dismissImagePickerController];
}

- (void)uploadImages{
    [self.imagesArr enumerateObjectsUsingBlock:^(UploadImageModel *item, NSUInteger idx, BOOL * _Nonnull stop) {
        [[GlobalManager shareGlobalManager] upyunUploadImage:item.originalImage andBlock:^(id data, NSError *error) {
            [self.imagesURLArr addObject:data];
            item.aliyunImageURL = data;
            dispatch_async(dispatch_get_main_queue(), ^(){
                [self.collectionView reloadData];
            });
        }];
    }];
}

- (void)dismissImagePickerController{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text{
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    NSInteger caninputlen = 300 - comcatstr.length;
    
    if (caninputlen >= 0){
        return YES;
    }else{
        NSInteger len = text.length + caninputlen;
        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
        NSRange rg = {0,MAX(len,0)};
        
        if (rg.length > 0){
            NSString *s = [text substringWithRange:rg];
            
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
        }
        return NO;
    }
}

- (void)textViewDidChange:(UITextView *)textView{
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    
    if (existTextNum > 300){
        //截取到最大位置的字符
        NSString *s = [nsTextContent substringToIndex:300];
        [textView setText:s];
    }
    //不让显示负数
    self.numberLabel.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,300 - existTextNum),300];
}

@end
